//
//  ShoppingProofVC.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/26.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import UIKit
import SVProgressHUD
protocol ShoppingProofDelegate: class {
    func didSuccessSale(success: Bool)
}

class ShoppingProofVC: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var wholePriceLabel: UILabel!
    @IBOutlet weak var imgView: UIImageView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var locationLabel: UILabel!
    
    var shoppingLists: [ShoppingList]!
    let helper = MaterialHelper()
    weak var delegate: ShoppingProofDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: "ShoppingProofCell", bundle: nil), forCellReuseIdentifier: "ShoppingProofCell")
        setUpView()
    }
    private func setUpView() {
        tableView.contentInset = UIEdgeInsetsMake(134, 0, 66, 0)
        var price: Double = 0
        for item in shoppingLists {
            price = price + Double(item.number)! * Double(item.price)!
        }
        
        wholePriceLabel.text = " 总价：\(price) "
        if let url = URL(string: Store.logo!) {
            imgView.kf.setImage(with: url)
        }
        locationLabel.text = Store.address
        nameLabel.text = Store.name
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        dateLabel.text = formatter.string(from: Date())
        let barItem = UIBarButtonItem(title: "确定销售", style: .plain, target: self, action: #selector(barItemTapped(_:)))
        navigationItem.setRightBarButton(barItem, animated: true)
    }
    
    @objc func barItemTapped(_ button: UIBarButtonItem!) {
        SVProgressHUD.show()
        var saleLists = [Sale.XiaoShou]()
        for item in shoppingLists {
            saleLists.append(Sale.XiaoShou(materialId: item.materialId, colorId: item.colorId, number: item.number, price: item.price, unit: item.unit))
        }
        let sale = Sale(buyerPhone: User.phoneNumber!, way: 0, sale: saleLists)
        let jsonEncoder = JSONEncoder()
        let data = try! jsonEncoder.encode(sale)
        helper.saleMaterial(with: data) { (error) in
            guard error == nil else {
                SVProgressHUD.showError(withStatus: error.debugDescription)
                self.delegate?.didSuccessSale(success: false)
                return
            }
            SVProgressHUD.showSuccess(withStatus: "销售成功！")
            SVProgressHUD.dismiss(withDelay: 1.5)
            self.delegate?.didSuccessSale(success: true)
            self.navigationController?.popViewController(animated: true)
        }
    }
}

extension ShoppingProofVC: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return shoppingLists.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ShoppingProofCell") as! ShoppingProofCell
        let shopping = shoppingLists![indexPath.row]
        cell.nameLabel.text = shopping.materialName
        cell.colorLabel.text = shopping.colorNo + "-" + shopping.color
        cell.numLabel.text = shopping.number
        cell.unitPriceLabel.text = shopping.price
        cell.allPriceLabel.text = "\(Double(shopping.number)! * Double(shopping.price)!)"
        cell.selectionStyle = .none
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 66
    }
}
